package org.agilelang.plugin.load;

/*
 AgileLang - A fourth generation language(http://www.agilelang.org).

 Copyright (C) 2013 Roderick Cusirramos (roderick20@hotmail.com)

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class ModifierClassPath {

    private static final String METODO_ADD_URL = "addURL";
    private static final Class[] PARAMETRO_METODO = new Class[]{URL.class};
    private final URLClassLoader loader;
    private final Method metodoAdd;

    public ModifierClassPath() throws NoSuchMethodException {
        loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        metodoAdd = URLClassLoader.class.getDeclaredMethod(METODO_ADD_URL, PARAMETRO_METODO);
        metodoAdd.setAccessible(true);
    }

    public URL[] getURLs() {
        return loader.getURLs();
    }

    public void addURL(URL url) {
        if (url != null) {
            try {
                metodoAdd.invoke(loader, new Object[]{url});
            } catch (Exception ex) {
                System.err.println("Excepcion al guardar URL: " + ex.getLocalizedMessage());
            }
        }
    }

    public void addURLs(URL[] urls) {
        if (urls != null) {
            for (URL url : urls) {
                addURL(url);
            }
        }
    }

    public void addArchivo(File archivo) throws MalformedURLException {
        if (archivo != null) {
            addURL(archivo.toURI().toURL());
        }
    }

    public void addArchivo(String nombreArchivo) throws MalformedURLException {
        addArchivo(new File(nombreArchivo));
    }
}
